//
//  ZMHomeCellPictureView.swift
//  ZMWeiboSwift
//
//  Created by pg on 2017/7/28.
//  Copyright © 2017年 pg. All rights reserved.
//

import UIKit
import SnapKit
import SDWebImage
//图片间距
let ItemMargin: CGFloat = 5

//计算每个图片的宽度
let ItemWidth = (UIScreen.main.bounds.size.width - 2*HomeCellMargin - 2*ItemMargin) / CGFloat(3)


class ZMHomeCellPictureView: UICollectionView ,UICollectionViewDataSource,UICollectionViewDelegate{

    //配图view的数据源
    var picUrlArray: [ZMPicUrlModel]? {
        didSet{
            
            //显示当前图片的个数
            pictureCountLabel.text = "\(picUrlArray?.count ?? 0)"
            //根据配图数量动态计算配图视图的size,每次一赋值的时候都需要跟新本身视图的size
            //由于只有在配图数量大于0的时候才会添加配图视图,因此代码如果执行到此处,配图数量肯定大于0,所以可以强制解包
            calculateSize(picCount: picUrlArray!.count)
            
            //数据发送跟新,就需要当前collectionview刷新数据
            self.reloadData()
        }
    }
    
    //懒加载布局对象
    var flowLayout: UICollectionViewFlowLayout
    
    
   //重写构造函数
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        flowLayout = UICollectionViewFlowLayout()
        //设置cell展示样式
        flowLayout.itemSize = CGSize(width: ItemWidth, height: ItemWidth)
        flowLayout.minimumLineSpacing = ItemMargin
        flowLayout.minimumInteritemSpacing = ItemMargin
       
        
        super.init(frame: frame, collectionViewLayout: flowLayout)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK:- 测试label的懒加载属性]
    fileprivate lazy var pictureCountLabel = UILabel()
    
    func setupUI() -> Void {
       
        //添加测试用得label,显示当前微博有几张配图
        self.addSubview(pictureCountLabel)
        pictureCountLabel.snp.makeConstraints { (make) in
            make.center.equalTo(self)
        }
        
        //设置代理和数据源
        dataSource = self
        delegate = self
        
        //注册cell
        self.register(ZMPictureCell.self, forCellWithReuseIdentifier: "cell")
        
    }
    
    //MARK:- 计算配图视图的大小
    func calculateSize(picCount:Int){
      
        //判断是否是单张图片,如果是,就是用单张图片的原始大小作为配图视图的大小
        if picCount == 1{
            //获取图片的地址
            let url = picUrlArray?.first?.thumbnail_pic
            //根据url获取图片下载大本地的缓存地址
            if let localImage = SDWebImageManager.shared().imageCache?.imageFromDiskCache(forKey: url){
                //获取本地缓存图片的size
                var imagesize = localImage.size
                //处理图片过窄
                if imagesize.width < 80{
                    //  图片的宽度
                    let imageWidth: CGFloat = 80
                    //  图片的高度
                    var imageHeight = imageWidth / localImage.size.width * localImage.size.height
                    
                    if imageHeight > 150 {
                        //  修改图片的高度
                        imageHeight = 150
                    }
                    //  计算后的大小
                    imagesize = CGSize(width: imageWidth, height: imageHeight)
                }
                
                //代码执行到此  说明单张图片一定存在,这时候 就需要使用单张图片的大小作为视图的大小
                self.snp.updateConstraints({ (make) in
                    make.size.equalTo(imagesize).priority(.high)
                })
                //将itemsize的大小给成图片的大小
                flowLayout.itemSize = imagesize
                
                return
            }
        }
        
        
        
        //计算列数
        let cols = picCount > 3 ? 3 : picCount
        //计算航速
        let rows = (picCount-1)/3 + 1
        
        //计算宽度
        let picViewWidth = CGFloat( cols) * ItemWidth + CGFloat(cols - 1)*ItemMargin
        
        //计算高度
        let picViewHeight = CGFloat( rows) * ItemWidth + CGFloat(rows - 1) * ItemMargin
        
        //跟新配图view的size
        self.snp.updateConstraints { (make) in
            make.size.equalTo(CGSize(width: picViewWidth, height: picViewHeight)).priority(.high)
        }
        
        
        flowLayout.itemSize = CGSize(width: ItemWidth, height: ItemWidth)
        
    }
    
    
    
    
    
}


extension ZMHomeCellPictureView: SDPhotoBrowserDelegate{
    
    //MARK:- collectionview数据源方法
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picUrlArray?.count ?? 0
    }
    
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! ZMPictureCell
        
        
        cell.homePic = picUrlArray![indexPath.row]
        
        return cell
        
        
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let photoBrowser = SDPhotoBrowser()
        photoBrowser.delegate = self
        photoBrowser.currentImageIndex = indexPath.item
        photoBrowser.imageCount = picUrlArray!.count
        photoBrowser.sourceImagesContainerView = self
        photoBrowser.show()
    }
    func photoBrowser(_ browser: SDPhotoBrowser!, highQualityImageURLFor index: Int) -> URL! {
        
        let urlStr = picUrlArray![index].thumbnail_pic!.replacingOccurrences(of: "thumbnail", with: "bmiddle")
        return URL(string: urlStr)
        
    }
    
    func photoBrowser(_ browser: SDPhotoBrowser!, placeholderImageFor index: Int) -> UIImage! {
        
        let cell = self.cellForItem(at: IndexPath(item: index, section: 0)) as! ZMPictureCell
        return cell.imageview.image
    }

}



